<template>
    <div class="full">
        <el-scrollbar>
            <div class="p-12 list-b-12">
                <CellBox title="授权委托书">
                    <TableBoxMx :data="{
                        tbody: table.tbody,
                        thead: [
                            {
                                label: '文件名称',
                                prop: 'fileName',
                                align: 'left',
                                width: null,
                            },
                            {
                                label: '文件类型',
                                prop: 'fileType',
                                align: 'center',
                                width: 100,
                            },
                            {
                                label: '文件大小',
                                prop: 'fileSize',
                                align: 'center',
                                width: 100,
                            },
                        ],
                        operation: [
                            {
                                label: '删除',
                                icon: 'Delete',
                                click: (row: any) => {
                                    proxy.$messageBox('是否删除当前数据，请确认！', () => {
                                        proxy.$api.ExcuteUploadFile.DeleteFileStorageByFileStorageCode({
                                            code: row.fileStorageCode,
                                        })
                                            .then((res: any) => {
                                                proxy.$message('删除成功');
                                                getTbody();
                                            })
                                            .catch(() => { });
                                    });

                                },
                            },
                            {
                                label: '下载',
                                icon: 'Download',
                                click: (row: any) => {
                                    downloadFile(row)
                                },
                            },
                        ]
                    }">
                        <template #fileSize="{ row }">
                            {{ fileSize(row.fileSize) }}
                        </template>
                    </TableBoxMx>
                </CellBox>
                <ElUploadBox isAuto @changeBtn="addBtn">
                    <el-button @click="addBtn" icon="Upload">上传文件</el-button>
                </ElUploadBox>
            </div>
        </el-scrollbar>
    </div>
</template>
<script setup lang="ts">
import '../pageCss.scss'; // 引入样式
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(
    defineProps<{
        data?: any;//数据源
        businessType?: any;//数据源
    }>(),
    {
    },
);
const list = ref([])
const table = reactive({
    search: {
        pageIndex: 1,
        pageSize: 99999,
    },
    tbody: []

})
const emit = defineEmits<{
    //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
    (event: 'saveBtn'): void;
}>();
const addBtn = (files: any, dataInfo: any) => {
    console.log(files);
    dataInfo.loading = false
    var formData = new FormData();
    formData.append("file", files.file);
    formData.append("relatedCode", props.data.baseData.productCode);
    formData.append("businessType", '授权委托书');
    proxy.$api.ExcuteUploadFile.UploadMoreFilesToFileStorage(formData)
        .then((res: any) => {
            proxy.$message('上传成功');
            getTbody()
        })
        .catch(() => { });
}
const downloadFile = async (row: any) => {
    const { fileUrl, fileName } = row;

    try {
        // 1. 使用 fetch 获取文件数据（自动处理跨域）
        // console.log(OutFileUrl);
        const response = await fetch(fileUrl);

        if (!response.ok) throw new Error('下载失败');

        // 2. 将响应转为 Blob
        const blob = await response.blob();

        // 4. 构造自定义文件名
        const downloadName = `${fileName}`;

        // 5. 创建 Blob URL
        const blobUrl = window.URL.createObjectURL(blob);

        // 6. 创建临时 a 标签触发下载
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = downloadName; // 此时 download 有效
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // 7. 释放 Blob URL
        window.URL.revokeObjectURL(blobUrl);
        proxy.$message('下载成功');
    } catch (error) {
        console.error('下载失败:', error);
    }
};
const fileSize = (bytes: number): string => {
    const units = ['', 'KB', 'MB', 'GB', 'TB'];
    if (bytes < 1) return '0 B';

    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    const value = bytes / Math.pow(1024, i);

    return `${value.toFixed(value < 10 ? 2 : 0)} ${units[i]}`;
}
const getTbody = () => {
    proxy.$api.ExcuteUploadFile.GetPageFileStorages({
        ...table.search,
        relatedCode: props.data.baseData.productCode,
    })
        .then((res: any) => {
            table.tbody = res.list
        })
        .catch(() => { });
}
onMounted(() => {
    getTbody()
});
</script>
